package com.lance.springbootes.utils;

import com.lance.springbootes.model.Goods;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname ParseJdHtml
 * @Description
 * @Date 2022/2/16 17:36
 * @Author lance
 */
public class ParseJdHtmlUtil {
    public static final String url = "https://search.jd.com/Search?keyword=%s";

    @SneakyThrows
    public static List<Goods> parseByKeyword(String keyword){
        Document document = Jsoup.parse(new URL(String.format(url,keyword)), 40000);
        Element goodsListUl = document.getElementById("J_goodsList");
        Elements goodsListLi = goodsListUl.getElementsByTag("li");
        return goodsListLi.stream().map(item -> {
                //获取li下 第一张图片
                String img = item.getElementsByTag("img").eq(0).attr("data-lazy-img");
                String name = item.getElementsByClass("p-name").eq(0).text();
                String price = item.getElementsByClass("p-price").eq(0).text();
                return Goods.builder().img(img).name(name).price(price).build();
            }
        ).collect(Collectors.toList());
    }

}
